<?php
namespace core;

class I18n
{
	/**
	 * Array of available languages
	 *
	 * @var	array
	 */
	private $languages = array();

	/**
	 * Array of available vocabularies
	 *
	 * @var unknown_type
	 */
	private $vocabularies = array();

	function __construct()
	{
		$this->languages = $this->languages = service("db")->
		Select("*")->
		From("_languages")->
		Run();
	}

	/**
	 * Translates given id into localized string of a selected vocabulary
	 *
	 * @param	integer		$id				I18n string id
	 * @param	string		$vocabulary		Vocabulary
	 */
	public function Translate($id, $vocabulary = "content", $language = false)
	{
		if (!isset($this->vocabularies[$vocabulary]))
		{
			$this->SetVocabulary($vocabulary);
		}

		if (!$language)
		{
			$language = $this->GetCurrentLanguage();
		}

		$language = $language['lang'];

		return $this->vocabularies[$vocabulary][$id][$language];
	}

	private function GetCurrentLanguage()
	{
		$id = core("Config")->GetConfigValue("default_lang");
		return $this->languages[$id];
	}

	private function VocabularyExists($vocabulary)
	{
		return isset($this->vocabularies[$vocabulary]);
	}

	private function SetVocabulary($vocabularyName)
	{
		$vocabulary = service("db")->Select("*")->From("_languages_".$vocabularyName)->run();

		$res = array();

		foreach ($vocabulary as $item)
		{
			$res[$item['id']] = $item;
		}

		$vocabulary = $res;

		if (is_array($vocabulary))
		{
			$this->vocabularies[$vocabularyName] = $vocabulary;
			return true;
		}
		else
		{
			service("debug")->error("Vocabulary $vocabularyName not found");
		}
	}
}